<template>
  <div class="app-container">
    <el-card>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
        <el-form-item label="题目标题" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-row :gutter="50">
          <el-col :lg="6" :md="12">
            <el-form-item label="题目分类" prop="classifyIds">
              <el-cascader v-model="ruleForm.classifyIds" :options="classifyOptions" clearable />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="时间限制(Sec)" prop="timeLimit">
              <el-input-number v-model="ruleForm.timeLimit" :controls="false" :precision="3" :min="0.5" :max="3" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="内存限制(MB)" prop="memoryLimit">
              <el-input-number v-model="ruleForm.memoryLimit" :controls="false" :min="32" :max="256" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label-width="120px" label="是否屏蔽" prop="defunct">
              <el-switch v-model="ruleForm.defunct" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="题目详情">
          <el-tabs ref="tabs" v-model="activeName" type="border-card">
            <el-tab-pane name="description" label="题目描述">
              <mavon-editor
                ref="description"
                v-model="ruleForm.description"
                :image-filter="uploadBefore"
                @imgAdd="addImage"
                @imgDel="delImage"
              />
            </el-tab-pane>
            <el-tab-pane name="input" label="输入说明">
              <mavon-editor
                ref="input"
                v-model="ruleForm.input"
                :image-filter="uploadBefore"
                @imgAdd="addImage"
                @imgDel="delImage"
              />
            </el-tab-pane>
            <el-tab-pane name="output" label="输出说明">
              <mavon-editor
                ref="output"
                v-model="ruleForm.output"
                :image-filter="uploadBefore"
                @imgAdd="addImage"
                @imgDel="delImage"
              />
            </el-tab-pane>
            <el-tab-pane name="sampleInput" label="样例输入">
              <el-input
                v-model="ruleForm.sampleInput"
                type="textarea"
                :autosize="{ minRows: 15, maxRows: 30}"
                placeholder="请输入标准的样例输入（可为空）"
              />
            </el-tab-pane>
            <el-tab-pane name="sampleOutput" label="样例输出">
              <el-input
                v-model="ruleForm.sampleOutput"
                type="textarea"
                :autosize="{ minRows: 15, maxRows: 30}"
                placeholder="请输入标准的样例输出"
              />
            </el-tab-pane>
            <el-tab-pane name="hint" label="提示">
              <mavon-editor
                ref="hint"
                v-model="ruleForm.hint"
                :image-filter="uploadBefore"
                @imgAdd="addImage"
                @imgDel="delImage"
              />
            </el-tab-pane>
            <el-tab-pane name="testInput" label="测试输入">
              <el-input
                v-model="ruleForm.testInput"
                type="textarea"
                :autosize="{ minRows: 15, maxRows: 30}"
                placeholder="请输入标准的测试输入（可为空），更多测试数据可在题目添加完成后在题目列表编辑处添加"
              />
            </el-tab-pane>
            <el-tab-pane name="testOutput" label="测试输出">
              <el-input
                v-model="ruleForm.testOutput"
                type="textarea"
                :autosize="{ minRows: 15, maxRows: 30}"
                placeholder="请输入标准的测试输出，更多测试数据可在题目添加完成后在题目列表编辑处添加"
              />
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  addProblem,
  addProblemImage,
  deleteProblemImage,
  getClassifyListCascader,
  getProblemAdminById,
  updateProblem
} from '@/api/problem'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { Message } from 'element-ui'

export default {
  components: {
    mavonEditor
  },
  data() {
    return {
      ruleForm: {
        title: '',
        defunct: false,
        timeLimit: 1.0,
        memoryLimit: 128,
        description: '',
        classifyId: '',
        classifyIds: '',
        input: '',
        output: '',
        sampleInput: '',
        sampleOutput: '',
        hint: '',
        testInput: '',
        testOutput: ''
      },
      problemId: -1,
      activeName: 'description',
      classifyOptions: [],
      rules: {
        title: [
          { required: true, message: '请输入题目标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        classifyIds: [
          { type: 'array', required: true, message: '请选择题目分类', trigger: 'change' }
        ],
        timeLimit: [
          { required: true, message: '请输入时间限制', trigger: 'blur' }
        ],
        memoryLimit: [
          { required: true, message: '请输入内存限制', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getClassifyListCascader()
  },
  mounted() {
    if (this.$route.query.problemId !== undefined) {
      this.problemId = this.$route.query.problemId
      this.getProblemAdminById()
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.classifyId = this.ruleForm.classifyIds[2]
          if (this.problemId === -1) {
            addProblem(this.ruleForm).then(res => {
              if (res.data) {
                Message.success({ showClose: true, message: '题目添加成功' })
              }
            })
          } else {
            updateProblem(this.ruleForm).then(res => {
              if (res.data) {
                Message.success({ showClose: true, message: '题目修改成功' })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    getProblemAdminById() {
      getProblemAdminById({ problemId: this.problemId }).then(res => {
        this.ruleForm = res.data
        this.ruleForm.defunct = res.data.defunct !== 'N'
      }).catch(err => {
        if (err.code === 'A0403') {
          this.$router.back()
        }
      })
    },
    getClassifyListCascader() {
      getClassifyListCascader()
        .then(res => {
          this.classifyOptions = res.data
        })
    },
    addImage(pos, file) {
      const formData = new FormData()
      formData.append('image', file)
      addProblemImage(formData).then(res => {
        this.$refs[this.activeName].$img2Url(pos, res.data)
      })
    },
    delImage(pos) {
      deleteProblemImage({ url: pos[0] }).then(res => {
        if (res.data) {
          Message.success({ showClose: true, message: '图片已删除' })
        }
      })
    },
    uploadBefore(file) {
      const af = file.name.split('.')[1]
      if (af !== 'jpg' && af !== 'jpeg' && af !== 'png' && af !== 'gif') {
        Message.error({ showClose: true, message: '图片格式限制为jpg,jpeg,png' })
        return false
      }
      if (file.size >= 20097152) {
        Message.error({ showClose: true, message: '图片最大为2M' })
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>

</style>
